%{

# include "readline.h"

static char *cmd = NULL;
static char **argv = NULL;
static int argc = 0;

static void gravar (char *text);
static char * tiraPelicas (const char *text);

%}

stringPelicas 		(\'[^\']*\')
stringNormal            ([^\t\n" "]+)
startString		^[^\t\n" "]+

%%

{startString}		{ cmd = strdup(yytext); }
{stringPelicas}		{ argc++; gravar(tiraPelicas(yytext)); }
{stringNormal}		{ argc++; gravar(strdup(yytext)); }
[\n\t" "]		{ ; }

%%

int yywrap () {
	return 1;
}

static void gravar (char *text) {
	int i;
	char **tmp = (char **) malloc(sizeof(char *)*argc);
	if (!tmp) 
		logMessage("io.cmd","readline.l","gravar","Memória Insuficiente",CRITICAL);
	for (i=0;i<(argc-1);i++) tmp[i] = argv[i];
	tmp[i] = text;
	free(argv);
	argv = tmp;
}
static char * tiraPelicas (const char *text) {
	int i, n = strlen(text);
	int k = 0;
	char *res = (char *) malloc(sizeof(char)*(n-1));
	for (i=1;i<(n-1);i++) res[k++] = text[i];
	res[k] = '\0';
	return res;
}

int parseCommand (const char *line) {
	// vou meter num ficheiro
	FILE *fp = tmpfile();
	int i;
	if (fp) {
		if (argc > 0) {
			for (i=0;i<argc;i++) free(argv[i]);
			argc = 0;
		}
		if (argv != NULL) { free(argv); argv = NULL; }
		if (cmd != NULL) { free(cmd); cmd = NULL; }
		fprintf(fp,"%s",line);
		fseek(fp,0,SEEK_SET);
		yyin = fp;
		yylex();
		fclose(fp); // apaga o ficheiro temporário...
		return 1;
	}
	else return 0;
}

char * getCommandName () {
	return cmd;
}
char ** getCommandArguments () {
	return argv;
}
int getNumberOfArguments () {
	return argc;
}
